package com.culturalCenter.dataCenter.controller.web;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.culturalCenter.dataCenter.Utils.*;
import com.culturalCenter.dataCenter.client.SdkClient;
import com.culturalCenter.dataCenter.customEntity.requestParam.PassengerFlowRequestParam;
import com.culturalCenter.dataCenter.customEntity.responseParam.passengerflow.*;
import com.culturalCenter.dataCenter.globalconfig.Interface.ApiVersion;
import com.culturalCenter.dataCenter.globalconfig.Interface.CustomVersion;
import com.culturalCenter.dataCenter.mapper.activity.ActivityServedNumberMapper;
import com.culturalCenter.dataCenter.mapper.site.SiteMapper;
import com.culturalCenter.dataCenter.schedule.passenger.TokenKeepAlive;
import com.culturalCenter.dataCenter.service.passengerflow.PassengerFlowLoginService;
import com.culturalCenter.dataCenter.service.passengerflow.PassengerFlowPopulationService;
import com.culturalCenter.dataCenter.vo.PassengerFlowVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import static com.culturalCenter.dataCenter.Utils.ApiResult.instance;

/**
 * 客流
 *
 * @Author zhao
 * @Date 2020/12/12 17:07
 */
@RestController
@RequestMapping("/{version}/passengerflow")
@Api(tags = "客流")
@ApiVersion(CustomVersion.VERSION_1)
@Slf4j
public class PassengerFlowController {

    private String userId = TokenKeepAlive.userIdPassengerFlow;
    private String userName = TokenKeepAlive.userNamePassengerFlow;
    private String token = TokenKeepAlive.tokenPassengerFlow;
    @Value("${passengerFlow.hostname}")
    private String hostname;
    @Resource
    private PassengerFlowLoginService passengerFlowLoginService;
    @Resource
    private PassengerFlowPopulationService passengerFlowPopulationService;
    @Resource
    private SiteMapper siteMapper;
    @Resource
    private ActivityServedNumberMapper activityServedNumberMapper;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private RestTemplate restTemplate;

    @Value("${zhaji.hostname1}")
    private String zhaJiHostname1;
    @Value("${zhaji.hostname}")
    private String zhaJiHostname;

    @Value("${zhaji.appid}")
    private String appid;
    @Value("${zhaji.secret}")
    private String secret;


    /**
     * 获取图创闸机数据登录的token
     *
     * @return token
     */
    //    @GetMapping("/testZhaJi")
    public void getZhaJiToken() {
        log.warn("从图创获取token...");
//        HttpHeaders headers = new HttpHeaders();
//        headers.add("x-key", xkey);
        Map<String, String> param = new HashMap<>();
        param.put("appid", appid);
        param.put("secret", secret);
        HttpEntity entity = new HttpEntity(param);
        JSONObject result = restTemplate.postForObject(zhaJiHostname, entity, JSONObject.class);
        log.warn("result：{}", result);
        String token = result.getJSONObject("data").getString("token");

        redisUtil.set("zhaji-token", token);
//        log.warn("图创闸机token：{}",token);
        return;
    }

    /**
     * 从图创获取预约系统今日数据
     *
     * @return
     */
    @GetMapping("/getZhaJiData")
    @ApiOperation(value = "预约系统数据:日", notes = "从图创获取预约系统今日数据")
    public String getZhaJiData() {
        String data = "";
        List<String> datas = new ArrayList<>();
        try {
            HttpHeaders headers = new HttpHeaders();
            String token = redisUtil.get("zhaji-token");
            headers.add("X-token", token);
            HttpEntity entity = new HttpEntity(headers);
            Date now = new Date();
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
            String start = sdf1.format(now) + " 00:00:00";
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String end = sdf2.format(now);
            ResponseEntity<JSONObject> result = restTemplate.exchange(zhaJiHostname1 + "?" + "startDate=" + start + "&endDate=" + end, HttpMethod.POST, entity, JSONObject.class);
//        log.info("result:{}",result);
            JSONObject body = result.getBody();
            data = body.getJSONObject("data").toJSONString();
            datas.add(data);
            return datas.toString();
        } catch (Exception e) {
            log.error("getZhaJiData:", e);
            getZhaJiToken();
        }
        Map<String, Integer> nullObj = new HashMap<>();
        nullObj.put("appointmentCount", 0);
        nullObj.put("inCount", 0);
        nullObj.put("outCount", 0);
        //        nullObj.put("register", 0);
//        nullObj.put("visited", 0);
        log.warn("未获取到图创token，请联系图创！");
//        JSONObject jsonObject = new JSONObject(nullObj);
        datas.add(JSON.toJSONString(nullObj));
//        log.warn("datas:{}", datas);
        return datas.toString();
    }

    /**
     * 从图创获取预约系统今年数据
     *
     * @return
     */
    @GetMapping("/getZhaJiDataYear")
    @ApiOperation(value = "预约系统数据：年", notes = "从图创获取预约系统今年数据")
    public String getZhaJiDataYear() {
        List<String> datas = new ArrayList<>();
        try {
            HttpHeaders headers = new HttpHeaders();
            String token = redisUtil.get("zhaji-token");
            headers.add("X-token", token);//将token设置进headers
            HttpEntity entity = new HttpEntity(headers);
            Date now = new Date();
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy");
            String start = sdf1.format(now) + "-01-01 00:00:00";
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String end = sdf2.format(now);

            ResponseEntity<JSONObject> result = restTemplate.exchange(zhaJiHostname1 + "?" + "startDate=" + start + "&endDate=" + end, HttpMethod.POST, entity, JSONObject.class);
//        log.info("result:{}",result);
            JSONObject body = result.getBody();
            String data = body.getJSONObject("data").toJSONString();

            datas.add(data);
            return datas.toString();
        } catch (Exception e) {
            log.error("getZhaJiDataYear:", e);
            getZhaJiToken();
        }
        Map<String, Integer> nullObj = new HashMap<>();
        nullObj.put("appointmentCount", 0);
        nullObj.put("inCount", 0);
        nullObj.put("outCount", 0);
//        nullObj.put("register", 0);
//        nullObj.put("visited", 0);
//        JSONObject jsonObject = new JSONObject(nullObj);
        datas.add(JSON.toJSONString(nullObj));
//        log.info("datas:{}",datas);
        return datas.toString();
    }

    /**
     * 从图创获取预约系统3.25起的数据
     *
     * @return
     */
    @GetMapping("/newZhaJiData")
    @ApiOperation(value = "预约系统数据：年", notes = "从图创获取预约系统今年数据")
    public String newZhaJiData() {
        List<String> datas = new ArrayList<>();
        try {
            HttpHeaders headers = new HttpHeaders();
            String token = redisUtil.get("zhaji-token");
            headers.add("X-token", token);//将token设置进headers
            HttpEntity entity = new HttpEntity(headers);
            Date now = new Date();
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy");
            String start = sdf1.format(now) + "-03-25 00:00:00";
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String end = sdf2.format(now);

            ResponseEntity<JSONObject> result = restTemplate.exchange(zhaJiHostname1 + "?" + "startDate=" + start + "&endDate=" + end, HttpMethod.POST, entity, JSONObject.class);
//        log.info("result:{}",result);
            JSONObject body = result.getBody();
            String data = body.getJSONObject("data").toJSONString();

            datas.add(data);
            return datas.toString();
        } catch (Exception e) {
            log.error("getZhaJiDataYear:", e);
            getZhaJiToken();
        }
        Map<String, Integer> nullObj = new HashMap<>();
        nullObj.put("appointmentCount", 0);
        nullObj.put("inCount", 0);
        nullObj.put("outCount", 0);
//        nullObj.put("register", 0);
//        nullObj.put("visited", 0);
//        JSONObject jsonObject = new JSONObject(nullObj);
        datas.add(JSON.toJSONString(nullObj));
//        log.info("datas:{}",datas);
        return datas.toString();
    }

    /**
     * 本年累计服务人次（大数据屏）
     *
     * @return
     */
    @GetMapping("/getServerYear")
    @ApiOperation(value = "本年服务人次", notes = "本年累计服务人次")
    public String getServerYear() {
        Map<String, Integer> number = new HashMap<>();
        List<String> datas = new ArrayList<>();
//        int all = 0;
//        int count = 0;
        Integer in = 0;
        try {
            HttpHeaders headers = new HttpHeaders();
            String token = redisUtil.get("zhaji-token");
            headers.add("X-token", token);
            HttpEntity entity = new HttpEntity(headers);
            Date now = new Date();
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy");
            String start = sdf1.format(now) + "-01-01 00:00:00";
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String end = sdf2.format(now);

            ResponseEntity<JSONObject> result = restTemplate.exchange(zhaJiHostname1 + "?" + "startDate=" + start + "&endDate=" + end, HttpMethod.POST, entity, JSONObject.class);
//        log.info("result:{}",result);
            JSONObject body = result.getBody();
            String data = body.getJSONObject("data").getString("inCount");
            in = Integer.parseInt(data);

        } catch (Exception e) {
            log.error("getServerYear:", e);
        }
//        List<ActivityServedNumbers> list = activityServedNumberMapper.queryAll();
//        for (ActivityServedNumbers numbers : list) {
//            count = count + numbers.getOnlinenumber() + numbers.getOfflinenumber();
//        }
//        all = in + count;
        number.put("serverNumbers", in);
        String s = JSON.toJSONString(number);
        datas.add(s);
//        log.info("datas:{}",datas);
        return datas.toString();

    }


    /**
     * 首页_客流报表
     * @return
     */
    @SneakyThrows
    @PostMapping("/indexPassengerFlow")
    @ApiOperation(value = "首页_客流", notes = "首页_客流")
    @ApiImplicitParams({@ApiImplicitParam(name = "param", value = "请求参数体", paramType = "body", dataType = "PassengerFlowRequestParam")})
    public ApiResult<PassengerFlowResponse> getIndexPassengerFlow(
//            @RequestBody @Valid PassengerFlowRequestParam param
    ) {
//        PassengerFlowIndexResponse response = new PassengerFlowIndexResponse();
//        List<PassengerFlowPopulationResponse> todayList = passengerFlowPopulationService.getReport(param);
//        if (CollectionUtils.isNotEmpty(todayList)) {
//            response.setTodayList(todayList);
//        }
//        // 上月（同时间）
//        param.setStatisticStartTime(TimeUtil.getTheDateLastMonth(param.getStatisticStartTime()));
//        param.setStatisticEndTime(TimeUtil.getTheDateLastMonth(param.getStatisticEndTime()));
//
//        List<PassengerFlowPopulationResponse> lastmonthList = passengerFlowPopulationService.getReport(param);
//        if (CollectionUtils.isNotEmpty(lastmonthList)) {
//            response.setLastmonthList(lastmonthList);
//        }
//        return ApiResult.instance(ResultCode.SUCCESS, response);

        // 查询当月每天的客流量
        List<PassengerFlowVo> currentMonthVos = passengerFlowPopulationService.getCurrentMonthReport("CurrentMonth");
        //查询上个月每天的客流量
        List<PassengerFlowVo> lastMonthVos = passengerFlowPopulationService.getCurrentMonthReport("lastMonth");
        LocalDate currentDate = LocalDate.now();
        LocalDate firstDayOfMonth = currentDate.withDayOfMonth(1);
        LocalDate lastMonthDate = currentDate.minusMonths(1);
        LocalDate firstDayOfLastMonth = lastMonthDate.withDayOfMonth(1);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M-d");
        LocalDate date = currentDate;
        //填补空数据
        while (date.isAfter(firstDayOfMonth) || date.isEqual(firstDayOfMonth)) {
            String format = date.format(formatter);
            boolean allContainDate = currentMonthVos.stream()
                    .anyMatch(PassengerFlowVo -> PassengerFlowVo.getShowTime().equals(format));
            if (!allContainDate) {
                PassengerFlowVo vo = new PassengerFlowVo();
                vo.setRemainder("0");
                vo.setShowTime(format);
                currentMonthVos.add(vo);
            }
            date = date.minusDays(1);
        }
        while (lastMonthDate.isAfter(firstDayOfLastMonth) || lastMonthDate.isEqual(firstDayOfLastMonth)) {
            String format = lastMonthDate.format(formatter);
            boolean b = lastMonthVos.stream().anyMatch(val -> val.getShowTime().equals(format));
            if (!b) {
                PassengerFlowVo vo = new PassengerFlowVo();
                vo.setRemainder("0");
                vo.setShowTime(format);
                lastMonthVos.add(vo);
            }
            lastMonthDate = lastMonthDate.minusDays(1);
        }
        //数据进行排序处理
        sort(currentMonthVos);
        sort(lastMonthVos);
        PassengerFlowResponse passengerFlowResponse = new PassengerFlowResponse();
        passengerFlowResponse.setTodayList(currentMonthVos);
        passengerFlowResponse.setLastmonthList(lastMonthVos);
        return instance(passengerFlowResponse);
        //TODO 客流系统没部署好，先返回假数据。客流系统部署好之后采用上面注释掉的代码
//        PassengerFlowIndexResponse response = new PassengerFlowIndexResponse();
//        // 今天数据（现在之前的才有数据）
//        List<PassengerFlowPopulationResponse> todayList = new ArrayList<>();
//        PassengerFlowPopulationResponse PopulationResponseToday = new PassengerFlowPopulationResponse();
//        String nowDate = param.getStatisticStartTime().substring(0, 10);
//        List<CustomPassengerFlowStatisticsInfo> statisticsInfoList = new ArrayList<>();
//        int nowHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
//        for (int i = 1; i <= nowHour; i++) {
//            CustomPassengerFlowStatisticsInfo statisticsInfo = new CustomPassengerFlowStatisticsInfo();
//            int max = 85;
//            int min = 60;
//            statisticsInfo.setRemainder((long) (new Random().nextInt(max) % (max - min + 1) + min));
//            statisticsInfo.setShowTime(i < 10 ? ("0" + i + ":00") : (i + ":00"));
//            statisticsInfoList.add(statisticsInfo);
//        }
//        PopulationResponseToday.setTime(nowDate);
//        PopulationResponseToday.setList(statisticsInfoList);
//        todayList.add(PopulationResponseToday);
//        response.setTodayList(todayList);
//        // 上月同日期数据
//        List<PassengerFlowPopulationResponse> lastMonthList = new ArrayList<>();
//        PassengerFlowPopulationResponse PopulationResponseToday1 = new PassengerFlowPopulationResponse();
//        String lastMonthDate = TimeUtil.getTheDateLastMonth(param.getStatisticStartTime()).substring(0, 10);
//        List<CustomPassengerFlowStatisticsInfo> statisticsInfoList1 = new ArrayList<>();
//        for (int i = 1; i < 25; i++) {
//            CustomPassengerFlowStatisticsInfo statisticsInfo = new CustomPassengerFlowStatisticsInfo();
//            int max = 85;
//            int min = 60;
//            statisticsInfo.setRemainder((long) (new Random().nextInt(max) % (max - min + 1) + min));
//            statisticsInfo.setShowTime(i < 10 ? ("0" + i + ":00") : (i + ":00"));
//            statisticsInfoList1.add(statisticsInfo);
//        }
//        PopulationResponseToday1.setTime(lastMonthDate);
//        PopulationResponseToday1.setList(statisticsInfoList1);
//        lastMonthList.add(PopulationResponseToday1);
//        response.setLastmonthList(lastMonthList);

//        return instance(response);
    }

    private void sort(List<PassengerFlowVo> list) {
    list.sort(new Comparator<PassengerFlowVo>() {
        @Override
        public int compare(PassengerFlowVo v1, PassengerFlowVo v2) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("M-d");
                Date date1 = sdf.parse(v1.getShowTime());
                Date date2 = sdf.parse(v2.getShowTime());
                return date1.compareTo(date2);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return 0;
        }
    });
    }

    /**
     * 查询所有区域编码（参数里的统计区域）、区域类型、区域名称、人数等信息
     */
    @SneakyThrows
    @PostMapping("/nowTimePopulation")
    @ApiOperation(value = "查询区域人数信息", notes = "获取区域编码（参数里的统计区域）、区域类型、区域名称、人数等信息")
    @ApiImplicitParams({@ApiImplicitParam(name = "siteCode", value = "siteCode", paramType = "query", dataType = "String", required = true)})
    public ApiResult<List<PassengerFlowRemainderResponse>> getNowTimePopulation(@RequestParam(required = false) String siteCode, @RequestBody(required = false) String searchKey) {
        /*List<PassengerFlowRemainderResponse> responseList = passengerFlowPopulationService.getAllRegions(searchKey);
        responseList.forEach(item -> {
            Integer galleryful = siteMapper.getGalleryfulBySiteCode(item.getRegionCode());
            item.setGalleryful(ObjectUtil.isEmpty(galleryful) ? 0 : galleryful);
        });
        return ApiResult.instance(ResultCode.SUCCESS, responseList);*/

        //TODO 客流系统没有部署好，先返回假数据。客流系统部署好之后采用上面注释掉的代码
        List<PassengerFlowRemainderResponse> responseList = new ArrayList<>();
        String[] regionName = {"一层", "报告厅", "培训厅", "展厅", "多功能厅", "非遗交流厅", "美术书法教室", "小型阶梯教室", "电子阅览室"};
        for (int i = 1; i < 45; i++) {
            PassengerFlowRemainderResponse response = new PassengerFlowRemainderResponse();
            response.setRegionCode(i < 10 ? ("00" + i) : ("0" + i));
            response.setRegionType(1);
            int index = (int) (Math.random() * regionName.length);
            response.setRegionName(regionName[index]);
            response.setEnterNumber(112);
            response.setOutNumber(42);
            // 在场人数,容纳人数
            if (i == 1) {
                response.setGalleryful(400);
                response.setRemainder(MathUtil.getRandomNumber(350, 450));
            } else if (i <= 6) {
                response.setGalleryful(70);
                response.setRemainder(MathUtil.getRandomNumber(50, 90));
            } else if (i <= 13) {
                response.setGalleryful(50);
                response.setRemainder(MathUtil.getRandomNumber(30, 75));
            } else if (i < 45) {
                response.setGalleryful(30);
                response.setRemainder(MathUtil.getRandomNumber(0, 50));
            }
            responseList.add(response);
        }

        // 如果是查询某个产地的数据则过滤掉其他场地数据
        if (StrUtil.isNotEmpty(siteCode)) {
            responseList = responseList.stream().filter(w -> w.getRegionCode().equals("021"))
                    .collect(Collectors.toList());
        }

        return instance(responseList);
    }

    /**
     * 查询今日总客流数（实时客流数）、在场总人数
     */
    @SneakyThrows
    @PostMapping("/totalPopulation")
    @ApiOperation(value = "查询今日总客流数、在场总人数", notes = "查询今日总客流数、在场总人数")
    @ApiImplicitParams({@ApiImplicitParam(name = "searchKey", value = "名称查询", paramType = "query", dataType = "String")})
    public ApiResult<List<PassengerFlowRemainderResponse>> getTotalPopulation(@RequestBody(required = false) String searchKey) {
        /*List<PassengerFlowRemainderResponse> responseList = passengerFlowPopulationService.getTotalPopulation();
        return ApiResult.instance(ResultCode.SUCCESS, responseList);*/

        //TODO 客流系统没有部署好，先返回假数据。客流系统部署好之后采用上面注释掉的代码
        List<PassengerFlowRemainderResponse> responseList = new ArrayList<>();
        PassengerFlowRemainderResponse response = new PassengerFlowRemainderResponse();
        response.setRegionCode("111");
        response.setRegionType(1);
        response.setRegionName("景区");

        Random random = new Random();
        int max = 245;
        int min = 195;
        int remainder = random.nextInt(max) % (max - min + 1) + min;
        response.setRemainder(remainder);

        // 当天进入人数
        // 每次调该接口人数都增加5~10个
        int varCount = random.nextInt(5) % (10 - 5 + 1) + 5;
        long expireTime = TimeUtil.getSecondsNextEarlyMorning();
        int initialNumber = !redisUtil.redisTemplate.hasKey("passengerFlowTotal") ? 212 : Integer.parseInt(redisUtil.get("passengerFlowTotal"));
        Integer enterNumber = initialNumber + varCount;
        redisUtil.setExpire("passengerFlowTotal", enterNumber.toString(), expireTime);
        response.setEnterNumber(enterNumber);
        response.setOutNumber(112);
        responseList.add(response);
        return instance(responseList);
    }

    /**
     * 大数据中心展示_区域信息
     */
    @SneakyThrows
    @GetMapping("/areaInfo")
    @ApiOperation(value = "大数据中心展示_区域信息", notes = "大数据中心展示_区域信息")
    public ApiResult<List<PassengerFlowAreaInfoResponse>> getAreaInfo() {
        /*List<PassengerFlowAreaInfoResponse> responseList = passengerFlowPopulationService.getAreaInfo();
        return ApiResult.instance(ResultCode.SUCCESS, responseList);*/

        //TODO 假数据
        List<PassengerFlowAreaInfoResponse> responseList = new ArrayList<>();
        String[] parentNames = {"公共文化中心", "翰墨园", "广府园", "广绣园", "曲艺园"};
        for (String parentName : parentNames) {
            PassengerFlowAreaInfoResponse response = new PassengerFlowAreaInfoResponse();
            response.setRegionCode(new Random().nextInt(10000) < 10 ? ("00" + new Random().nextInt(10000)) : ("0" + new Random().nextInt(10000)));
            response.setRegionName(parentName);
            response.setRemainder(new Random().nextInt(10000));
            response.setParentCode("0");
            response.setOverrun(new Random().nextBoolean() ? 1 : 0);
            responseList.add(response);
        }
        String[] regionNames = {"一层", "报告厅", "培训厅", "展厅", "多功能厅", "非遗交流厅", "美术书法教室", "小型阶梯教室", "电子阅览室"};
        List<PassengerFlowAreaInfoResponse> copyList = new ArrayList<>();
        for (PassengerFlowAreaInfoResponse infoResponse : responseList) {
            String regionName = infoResponse.getRegionName();
            int num = Objects.equals(regionName, "公共文化中心") ? 27 : 2;
            for (int i = 1; i < num; i++) {
                PassengerFlowAreaInfoResponse response = new PassengerFlowAreaInfoResponse();
                response.setRegionCode(i < 10 ? ("00" + i) : ("0" + i));
                int index = (int) (Math.random() * regionNames.length);
                response.setRegionName(regionNames[index]);
                response.setParentCode(infoResponse.getRegionCode());
                if (i == 1) {
                    response.setRemainder(MathUtil.getRandomNumber(350, 450));
                } else if (i <= 6) {
                    response.setRemainder(MathUtil.getRandomNumber(50, 90));
                } else if (i <= 13) {
                    response.setRemainder(MathUtil.getRandomNumber(30, 75));
                } else if (i < 45) {
                    response.setRemainder(MathUtil.getRandomNumber(0, 50));
                }
                response.setOverrun(new Random().nextBoolean() ? 1 : 0);
                copyList.add(response);
            }
        }
        responseList.addAll(copyList);
        return ApiResult.instance(ResultCode.SUCCESS, responseList);
    }

    /**
     * 第三方接口登录信息（无用，官方依赖会自动根据.properties文件登录）
     */
    @SneakyThrows
    @Deprecated
    @PostMapping("/login")
    @ApiOperation(value = "获取第三方接口登录信息（这个接口用不到了）", notes = "根据帐号和密码获取参数userId(id)、userName（loginName）、token(token)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userName", value = "账号", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "password", value = "密码", paramType = "query", dataType = "String", required = true)})
    public ApiResult<PassengerFlowLoginInfoResponse> getLoginInfo(@RequestParam String userName, @RequestParam String password) {
        /*PassengerFlowLoginInfoResponse passengerFlowLoginInfoResponse = passengerFlowLoginService.getLoginReturnInfo(userName, password);
        return ApiResult.instance(ResultCode.SUCCESS, passengerFlowLoginInfoResponse);*/

        //TODO 客流系统没部署好，先返回假数据。客流系统部署好之后采用上面注释掉的代码
        PassengerFlowLoginInfoResponse response = new PassengerFlowLoginInfoResponse();
        response.setId("1");
        response.setLoginName("system");
        response.setToken("eb1fd938a48ab74e2ea0509801277429");
        return instance(response);
    }

    /**
     * 实时人数统计：按小时
     */
    @SneakyThrows
    @PostMapping("/realTimePopulationHour")
    @ApiOperation(value = "（首页）实时人数统计：按小时", notes = "实时人数统计：按小时")
    @ApiImplicitParams({@ApiImplicitParam(name = "param", value = "请求参数体", paramType = "body", dataType = "PassengerFlowRequestParam")})
    public ApiResult<List<PassengerFlowPopulationResponse>> getRealtimePopulationHour(@RequestBody @Valid PassengerFlowRequestParam
                                                                                              param) {
        String timeType = "hour";
        List<PassengerFlowPopulationResponse> listHour = passengerFlowPopulationService.getRealTimeData(userId, userName, token, param, timeType);
        return instance(ResultCode.SUCCESS, listHour);
    }

    /**
     * 实时人数统计：按天(新API无此接口，暂时搁置)
     */
    @SneakyThrows
    @PostMapping("/realTimePopulationDay")
    @ApiOperation(value = "实时人数统计：按天", notes = "实时人数统计：按天")
    @ApiImplicitParams({@ApiImplicitParam(name = "param", value = "请求参数体", paramType = "body", dataType = "PassengerFlowRequestParam")})
    public ApiResult<List<PassengerFlowPopulationResponse>> getRealtimePopulationDay(@RequestBody @Valid PassengerFlowRequestParam param) {
        String timeType = "day";
        List<PassengerFlowPopulationResponse> listDay = passengerFlowPopulationService.getRealTimeData(userId, userName, token, param, timeType);
        return instance(ResultCode.SUCCESS, listDay);
    }

    /**
     * 实时人数统计：按月(新API无此接口，暂时搁置)
     */
    @SneakyThrows
    @PostMapping("/realTimePopulationMonth")
    @ApiOperation(value = "实时人数统计：按月", notes = "实时人数统计：按月")
    @ApiImplicitParams({@ApiImplicitParam(name = "param", value = "请求参数体", paramType = "body", dataType = "PassengerFlowRequestParam")})
    public ApiResult<List<PassengerFlowPopulationResponse>> getRealtimePopulationMonth(@RequestBody @Valid PassengerFlowRequestParam param) {
        String timeType = "month";
        List<PassengerFlowPopulationResponse> listMonth = passengerFlowPopulationService.getRealTimeData(userId, userName, token, param, timeType);
        return instance(ResultCode.SUCCESS, listMonth);
    }

    /**
     * 实时人数统计：按年(新API无此接口，暂时搁置)
     */
    @PostMapping("/realTimePopulationYear")
    @ApiOperation(value = "实时人数统计：按年", notes = "实时人数统计：按年")
    @ApiImplicitParams({@ApiImplicitParam(name = "param", value = "请求参数体", paramType = "body", dataType = "PassengerFlowRequestParam")})
    public String getRealtimePopulationYear(@RequestBody @Valid PassengerFlowRequestParam param) {
        try {
            Map<String, String> headMap = new HashMap<>();
            headMap.put("content-Type", "application/json");
            String url = hostname + "/CardSolution/statistics/realTimeReport/chart/year?userId=" + userId + "&userName=" + userName + "&token=" + token;
            return SdkClient.post(url, JSON.toJSONString(param), headMap);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            LogException.LogError(log, e);
            return JSON.toJSONString(instance(ResultCode.FALL));
        }
    }

    /**
     * 进出人数统计：按小时
     */
    @SneakyThrows
    @PostMapping("/inAndOutPopulationHour")
    @ApiOperation(value = "进出人数统计：按小时", notes = "进出人数统计：按小时")
    @ApiImplicitParams({@ApiImplicitParam(name = "param", value = "请求参数体", paramType = "body", dataType = "PassengerFlowRequestParam")})
    public ApiResult<Map<String, List<PassengerFlowPopulationResponse>>> getInAndOutPopulation(@RequestBody @Valid PassengerFlowRequestParam param) {
        String timeType = "hour";
        Map<String, List<PassengerFlowPopulationResponse>> mapHour = passengerFlowPopulationService.getInAndOutData(userId, userName, token, param, timeType);
        return instance(ResultCode.SUCCESS, mapHour);
    }

    /**
     * 进出人数统计：按天
     */
    @SneakyThrows
    @PostMapping("/inAndOutPopulationDay")
    @ApiOperation(value = "进出人数统计：按天", notes = "进出人数统计：按天")
    @ApiImplicitParams({@ApiImplicitParam(name = "param", value = "请求参数体", paramType = "body", dataType = "PassengerFlowRequestParam")})
    public ApiResult<Map<String, List<PassengerFlowPopulationResponse>>> getInAndOutPopulationDay(@RequestBody @Valid PassengerFlowRequestParam param) {
        String timeType = "day";
        Map<String, List<PassengerFlowPopulationResponse>> mapDay = passengerFlowPopulationService.getInAndOutData(userId, userName, token, param, timeType);
        return instance(ResultCode.SUCCESS, mapDay);
    }

    /**
     * 进出人数统计：按月
     */
    @SneakyThrows
    @PostMapping("/inAndOutPopulationMonth")
    @ApiOperation(value = "进出人数统计：按月", notes = "进出人数统计：按月")
    @ApiImplicitParams({@ApiImplicitParam(name = "param", value = "请求参数体", paramType = "body", dataType = "PassengerFlowRequestParam")})
    public ApiResult<Map<String, List<PassengerFlowPopulationResponse>>> getInAndOutPopulationMonth(@RequestBody @Valid PassengerFlowRequestParam param) {
        String timeType = "month";
        Map<String, List<PassengerFlowPopulationResponse>> mapMonth = passengerFlowPopulationService.getInAndOutData(userId, userName, token, param, timeType);
        return instance(ResultCode.SUCCESS, mapMonth);
    }

    /**
     * 进出人数统计：按年
     */
    @PostMapping("/inAndOutPopulationYear")
    @ApiOperation(value = "进出人数统计：按年", notes = "进出人数统计：按年")
    @ApiImplicitParams({@ApiImplicitParam(name = "param", value = "请求参数体", paramType = "body", dataType = "PassengerFlowRequestParam")})
    public String getInAndOutPopulationYear(@RequestBody @Valid PassengerFlowRequestParam param) {
        try {
            Map<String, String> headMap = new HashMap<>();
            headMap.put("content-Type", "application/json");
            String url = hostname + "/CardSolution/statistics/inAndOutReport/chart/year?userId=" + userId + "&userName=" + userName + "&token=" + token;
            return SdkClient.post(url, JSON.toJSONString(param), headMap);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            LogException.LogError(log, e);
            return JSON.toJSONString(instance(ResultCode.FALL));
        }
    }

    /**
     * 查询人员身份、部门
     */
    @SneakyThrows
    @Deprecated
    @PostMapping("/identityAndDepartment")
    @ApiOperation(value = "查询人员身份、部门", notes = "查询人员身份、部门（这个接口暂时用不到）")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "人员id", paramType = "query", dataType = "long", required = true)})
    public ApiResult<List<PassengerFlowIdentityInfoResponse>> getIdentityAndDepartment(@RequestParam long id) {
        List<PassengerFlowIdentityInfoResponse> responseList = passengerFlowPopulationService.getIdentityAndDepartment(userId, userName, token, id);
        return instance(ResultCode.SUCCESS, responseList);
    }

    /**
     * 获取客流跳板数据写入redis
     */
    @SneakyThrows
    @Deprecated
    @PostMapping(value = "/jumpData", produces = {"application/json;charset=UTF-8"})
    @ApiOperation(value = "跳板数据", notes = "跳板数据写入redis")
    @ApiImplicitParams({@ApiImplicitParam(name = "psfData", value = "请求参数体", paramType = "body", dataType = "String")})
    public ApiResult setBridgeData(@RequestBody String psfData) {
        if (psfData != null) {
            try {
                redisUtil.set("passengerFlowAreaData", psfData);
//                log.info("接收到bridge信息，写入redis成功");
            } catch (RuntimeException e) {
                e.printStackTrace();
            }
        } else {
            return instance(ResultCode.FALL);
        }
        return instance(ResultCode.SUCCESS);
    }

    @PostMapping("/getJumpData")
    @ApiOperation(value = "跳板数据", notes = "从redis中获取跳板数据")
    public String getBridgeDataTest() {
//        log.info("从redis中获取跳板客流数据");
        String areaData = redisUtil.get("passengerFlowAreaData");

        //JSONObject jsonObject = JSONObject.parseObject(areaData);
        return areaData;
    }


}
